package pa165.dominatingspecies.frontend.environment;

import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.access.prepost.PreAuthorize;
import pa165.dominating.species.enums.ElementType;
import pa165.dominating.species.tos.ElementTo;
import pa165.dominating.species.tos.EnvironmentTo;
import pa165.dominatingspecies.frontend.element.EnumPropertyModel;

import pa165.dominatingspecies.frontend.pages.BasePage;

import pa165.dominatingspecies.service.impl.EnvironmentServiceImpl;

/**
 *
 * @author Stanislau Dubrouski
 */
@PreAuthorize("hasRole('WORKER')")
public class EnvironmentDetailsPage extends BasePage {

    @SpringBean(name = "environmentService")
    private EnvironmentServiceImpl envService;

    private EnvironmentTo env;

    private List<ElementTo> selected = new ArrayList<>();

    EnvironmentDetailsPage(Long id) {
        if (id != null) {
            env = envService.getEnvironmentById(id);
            selected = env.getElements();
        }

        add(new Label("envName", env.getName()));
        add(new Label("envDesc", env.getDescription()));

        ListView<ElementTo> envsElems = new ListView<ElementTo>("envsElems", createModelForElements()) {
            @Override
            protected void populateItem(ListItem<ElementTo> item) {
                final ElementTo ele = (ElementTo) item.getModelObject();
                item.add(new Label("id", new PropertyModel(item.getModel(), "id")));
                item.add(new Label("type", new EnumPropertyModel<ElementType>(ele, "type", this)));
            }
        };
        add(envsElems);

        add(new BackToListLink("backToList"));
        add(new EditEnvironmentLink("edit", env.getId()));

    }

    private LoadableDetachableModel<List<ElementTo>> createModelForElements() {
        return new LoadableDetachableModel<List<ElementTo>>() {
            @Override
            protected List<ElementTo> load() {
                return selected;
            }
        };
    }
}
